package com.xxmw.transaction.common.utils;

/**
 * @author luowenliang
 * @since 2020/2/5 17:07
 */
public class StringUtil {

    public static String str2Hex(String str) {
        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }
    
    /**
     * 生成固定大小的随机验证码
     * @param size
     * @return
     */
    public static String code(int size) {
        if(size == 0) {
            size = 6;
        }
        int[] random = new int[size];
        for(int i=0;i<size;i++) {
            while(true) {
                int rand = (int)(Math.random()*size);
                for(int j=0;j<i;j++) {
                    if(random[j] == rand) {
                        rand = -1;
                        break;
                    }
                }
                if(rand != -1) {
                    random[i] = rand;
                    break;
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<size;i++) {
            builder.append(String.valueOf(random[i]));
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        System.out.println(str2Hex("KgqEjXaSCkJRkMXyxQm0XvcwlW+sUzHHmpiGcSI/02c="));
    }
}
